package de.koller.planet2D.frame.previewRender;

import de.koller.planet2D.aRenderer.PrimitivRenderStep;
import de.koller.planet2D.container.FrameClip;
import de.koller.planet2D.container.RenderObj;
import de.koller.planet2D.container.TextureValue;
import de.koller.planet2D.frame.ObjectFrame;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;

public class BasicRenderer extends RenderNode {

	private double gripradius = 0;
	
	synchronized public void renderBasics() {
		for( RenderObj o : proot.renderContainer.renderObjects )
			render( o );
	}
	
	synchronized public void renderGrips() {
		for( RenderObj o : proot.renderContainer.renderObjects )
			renderGrip( o );
	}
	
	private void render( RenderObj o ) {
		Graphics2D g = getGraphics();
		
		if( o.getTextureEntity() != null && o.getTextureEntity().textureInPreview )
			renderTexture( o );
	}
	
	private void renderTexture( RenderObj o ) {
		Graphics2D g = getGraphics();
		PrimitivRenderStep.renderTexture( o, g, proot.renderContainer.textur );
	}
	
	private void renderGrip( RenderObj o ) {
		Graphics2D g = getGraphics();
		
		AffineTransform a = g.getTransform();
		
		g.setStroke( new BasicStroke( 0 ) );
		g.rotate( Math.toRadians( o.rotation ), o.position.getX(), o.position.getY() );
		
		
		if( o instanceof FrameClip ) {
			g.setColor( Color.ORANGE );
			g.draw( new Rectangle2D.Double( o.position.getX() - o.size.getX() / 2 - o.size.getX(), 
										o.position.getY() - o.size.getY() / 2 - o.size.getY(), 
										o.size.getX()*3, o.size.getY()*3 ) );
			
			g.setColor( Color.RED );
			g.draw( new Rectangle2D.Double( o.position.getX() - o.size.getX() / 2, 
										o.position.getY() - o.size.getY() / 2, 
										o.size.getX(), o.size.getY() ) );
		} else {
			g.setColor( Color.WHITE );
			g.draw( new Rectangle2D.Double( o.position.getX() - o.size.getX() / 2, 
										o.position.getY() - o.size.getY() / 2, 
										o.size.getX(), o.size.getY() ) );
		}
		
		g.setTransform( a );
		g.setStroke( new BasicStroke( 0 ) );
		
		double s = this.renderRoot.camera.scale;
		gripradius = 4. / s;
		Shape h = new Ellipse2D.Double( o.position.getX() - gripradius, o.position.getY() - gripradius,
				gripradius*2, gripradius*2 );

		ObjectFrame c = proot.previewFrame.getCurrentObjFrame();
		if( c != null && c.renderObj == o )
			g.setColor( Color.YELLOW );
		else
			g.setColor( Color.GRAY );
		
		g.fill( h );
		g.setColor( Color.BLACK );
		g.draw( h );
	}
	
	public double lastUsedGripRadius() {
		return gripradius;
	}
}
